package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.message.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApThreadLocal;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String ,String> kafkaTemplate;

    /**
     * 保存阅读行为
     * 1. 阅读行为不需要回显和查询, 所以不需要保存到redis, 直接保存到数据库即可
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {

        //1.校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录用户id
        ApUser apUser = ApThreadLocal.getApUser();
        //表示未登录
        if(apUser==null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if(apUser.getId()==0){
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }


        //3.查询mongo中是否有数据，如果有，则更新次数，否则新增
        ApReadBehavior readBehavior = mongoTemplate.findOne(
                Query.query(Criteria.where("userId").is(apUser.getId())
                        .and("articleId").is(dto.getArticleId()))
                , ApReadBehavior.class);
        if(readBehavior==null){
            //3.新增mongo
            readBehavior=new ApReadBehavior();
            BeanUtils.copyProperties(dto,readBehavior);
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setUserId(apUser.getId().longValue());
            readBehavior.setId(ObjectId.get().toHexString());
            readBehavior.setCount(1);
        }else {
            //更新次数和时间
            readBehavior.setCount(readBehavior.getCount()+dto.getCount());
            readBehavior.setUpdatedTime(new Date());
        }
        mongoTemplate.save(readBehavior);




        //发送消息
        UpdateArticleMess mess=new UpdateArticleMess();
        mess.setAdd(1);
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setArticleId(dto.getArticleId());

        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
